package handler

import (
	"ecommerce-customer-support-chat/api/request"
	"ecommerce-customer-support-chat/inter/dao"
	model2 "ecommerce-customer-support-chat/inter/model"
	"ecommerce-customer-support-chat/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model2.Users
	dao.GetOneByFields(&model2.Users{}, &user)
	if user.Account == req.Account {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "此账号已存在",
			"data": nil,
		})
		return
	}
	user = model2.Users{
		Account:  req.Account,
		PassWord: req.Password,
		Email:    req.Email,
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": user,
	})
}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var user model2.Users
	dao.GetOneByFields(&model2.Users{}, &user)
	if user.Account != req.Account {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "没有此账号",
			"data": nil,
		})
		return
	}
	claims := pkg.CustomClaims{ID: uint(user.Id)}
	jwt := pkg.NewJWT("token")
	token, err := jwt.CreateToken(claims)
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": token,
	})
}
